package com.bj58.analysis.tools;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.bj58.analysis.tools.common.CookieIdUtils;
import com.bj58.analysis.tools.common.GetObjectToClassUtils;
import com.bj58.analysis.tools.common.URLDecodeUtils;
import com.bj58.analysis.tools.common.bean.LogBean;
import com.bj58.analysis.tools.original.bean.OriginalTrackBean;

public class OriginalAppTrackAnalysis extends CommonAnalysis {
	private static final String PAGETYPE_RULE_LIST = "\"pagetype\":\"list\"";
	private static final String PAGETYPE_RULE_DETAIL = "\"pagetype\":\"detail\"";
	private static final String PAGETYPE_RULE_MYJOB = "\"pagetype\":\"myjob\"";
	private static final String PAGETYPE_RULE_PREFERRED = "\"pagetype\":\"preferred\"";
	private static final String PAGETYPE_RULE_SCHOOL = "\"pagetype\":\"schoolrecruit\"";
	private static final String PAGETYPE_RULE_MAIN = "\"pagetype\":\"main\"";
	private static final String ACTIONTYPE_RULE_ENTER = "\"actiontype\":\"enter\"";
	private static final String ACTIONTYPE_RULE_NEXT = "\"actiontype\":\"nextpage\"";
	private static final String ACTIONTYPE_RULE_SHOW = "\"actiontype\":\"show\"";

	@Override
	protected LogBean analysis(String logLine) {
		OriginalTrackBean bean = null;
		if (StringUtils.isNotBlank(logLine)) {
			 if ((logLine.contains(PAGETYPE_RULE_LIST) && logLine
			 .contains(ACTIONTYPE_RULE_ENTER))
			 || (logLine.contains(PAGETYPE_RULE_LIST) && logLine
			 .contains(ACTIONTYPE_RULE_NEXT))
			 || (logLine.contains(PAGETYPE_RULE_DETAIL) && logLine
			 .contains(ACTIONTYPE_RULE_SHOW))
			 || logLine.contains(PAGETYPE_RULE_MYJOB)
			 || logLine.contains(PAGETYPE_RULE_PREFERRED)
			 || logLine.contains(PAGETYPE_RULE_SCHOOL)) {

			String[] logLines = logLine.split("\001", -1);
			int length = logLines.length;
			if (length >= 26) {
				Map<String, String> map = new HashMap<String, String>();
				String cookieId = logLines[15];
				if (StringUtils.isBlank(cookieId) || cookieId.equals("-")
						|| cookieId.length() < 10) {
					cookieId = CookieIdUtils.getCookieIdOfRand();
				}
				map.put("cookieID", cookieId);// cookieId
				map.put("loginUid", logLines[1].trim());// 用户登录id
				map.put("userIp", logLines[2].trim());// 用户ip

				String tmpEpoch = logLines[5].trim();// 时间戳
				if (StringUtils.isNotBlank(tmpEpoch) && tmpEpoch.length() == 13) {
					String epoch = tmpEpoch.substring(0, 10) + "."
							+ tmpEpoch.substring(10);
					map.put("epoch", epoch);
				}

				map.put("catePath", logLines[6].trim());
				String areaPath = logLines[7].trim().replace("\"", "");
				map.put("areaPath", areaPath);

				// url
				String url = URLDecodeUtils.parser(logLines[10]);
				if (StringUtils.isNotBlank(url))
					map.put("url", url);

				// referer
				String referer = URLDecodeUtils.parser(logLines[12]);
				if (StringUtils.isNotBlank(referer))
					map.put("referrer", referer);

				// pagetype
				String trackUrl = logLines[11].trim();
				if (StringUtils.isNotBlank(trackUrl)
						&& trackUrl.contains("pagetype")) {
					String pagetype = StringUtils.substringBetween(trackUrl,
							"\"pagetype\":\"", "\",");
					if (StringUtils.isNotBlank(pagetype))
						map.put("pageType", pagetype);
				}

				JSONObject trackUrlObj = new JSONObject();
				if (StringUtils.isNotBlank(trackUrl) && !(trackUrl.equals("-"))) {
					try {
						JSONObject tmpTrackUrlJson = JSONObject
								.fromObject(trackUrl);
						addJson(trackUrlObj, tmpTrackUrlJson);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				trackUrlObj.put("area", areaPath);

				// 备用字段json格式
				String backup = logLines[8].trim();
				if (StringUtils.isNotBlank(backup) && !(backup.equals("-"))) {
					try {
						JSONObject backupJson = JSONObject.fromObject(backup);
						addJson(trackUrlObj, backupJson);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// 无线自由json字符串
				String wuxian_data = logLines[13].trim();
				if (StringUtils.isNotBlank(wuxian_data)
						&& !(wuxian_data.equals("-"))) {
					wuxian_data = wuxian_data.replace("\"{", "{").replace(
							"}\"", "}");
					try {
						JSONObject wuxian_dataJson = JSONObject
								.fromObject(wuxian_data);
						addJson(trackUrlObj, wuxian_dataJson);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// uuid
				String uuid = logLines[14].trim();
				if (StringUtils.isNotBlank(uuid))
					trackUrlObj.put("UUID", uuid);

				// imei
				String imei = logLines[15].trim();
				if (StringUtils.isNotBlank(imei))
					trackUrlObj.put("IMEI", imei);

				// 产品编号
				String productorid = logLines[16].trim();
				if (StringUtils.isNotBlank(productorid))
					trackUrlObj.put("productorId", productorid);

				// 用户所属渠道id
				String channelid = logLines[17].trim();
				if (StringUtils.isNotBlank(channelid))
					trackUrlObj.put("channelId", channelid);

				// 用户的设备型号
				String deviceM = logLines[18].trim();
				if (StringUtils.isNotBlank(deviceM))
					trackUrlObj.put("deviceM", deviceM);

				// 客户端的版本名
				String clientVersion = logLines[19].trim();
				if (StringUtils.isNotBlank(clientVersion))
					trackUrlObj.put("clientVersion", clientVersion);

				// 用户的操作系统名称
				String os = logLines[20].trim();
				if (StringUtils.isNotBlank(os))
					trackUrlObj.put("OS", os);

				// 用户的操作系统版本号
				String osV = logLines[21].trim();
				if (StringUtils.isNotBlank(osV))
					trackUrlObj.put("OSV", osV);

				// 用户的网络环境
				String userNetwork = logLines[22].trim();
				if (StringUtils.isNotBlank(userNetwork))
					trackUrlObj.put("userNetwork", userNetwork);

				// 日志上传的时间，格式是 yyyyMMddHHmmss
				String uploadTime = logLines[23].trim();
				if (StringUtils.isNotBlank(uploadTime))
					trackUrlObj.put("uploadTime", uploadTime);

				// 用户所在的经度
				String longitude = logLines[24].trim();
				if (StringUtils.isNotBlank(longitude))
					trackUrlObj.put("longitude", longitude);

				// 用户所在的纬度
				String latitude = logLines[25].trim();
				if (StringUtils.isNotBlank(latitude))
					trackUrlObj.put("latitude", latitude);

				if (length >= 28) {
					// 用户设备分辨率
					String windowSize = logLines[27].trim();
					if (StringUtils.isNotBlank(windowSize))
						map.put("windowSize", windowSize);

					// 用户地址
					String cAddress = logLines[27].trim();
					if (StringUtils.isNotBlank(cAddress))
						trackUrlObj.put("cAddress", cAddress);
				}

				if (length >= 29) {
					// 竞品信息
					String ak47 = logLines[28].trim();
					if (StringUtils.isNotBlank(ak47))
						trackUrlObj.put("ak47", ak47);
				}

				trackUrlObj.put("appPv", "1");

				String tmpTrackUrl = trackUrlObj.toString();
				map.put("trackUrl", tmpTrackUrl);

				if (map != null && map.size() != 0) {
					Object obj = GetObjectToClassUtils.getObjectByMap(
							OriginalTrackBean.class, map);
					if (obj != null)
						bean = (OriginalTrackBean) obj;
				}
			}
			 }
		}
		return bean;
	}

	// 将子json串添加到主json对象中
	private void addJson(JSONObject allJson, JSONObject tmpJson) {
		Set<String> tmpKeySet = tmpJson.keySet();
		for (String str : tmpKeySet) {
			Object obj = tmpJson.get(str);
			if (obj instanceof JSONObject) {
				JSONObject oJson = (JSONObject) obj;
				addJson(allJson, oJson);
			} else if (obj instanceof JSONArray) {
				StringBuffer buffer = new StringBuffer();
				JSONArray arrayJson = (JSONArray) obj;
				List list = JSONArray.toList(arrayJson);
				int number = list.size();
				for (int i = 0; i < number; i++) {
					Object tmpObj = list.get(i);
					if (tmpObj instanceof String) {
						buffer.append(tmpObj);
						if (i != (number - 1))
							buffer.append(",");
					}
				}
				allJson.put(str, buffer.toString());
			} else {
				allJson.put(str, obj);
			}
		}
	}
}
